{% extends "base.html" %}

{% block title %}策略管理 - XCQuant{% endblock %}

{% block breadcrumb %}
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="{{ url_for('index') }}">首页</a></li>
        <li class="breadcrumb-item active">策略管理</li>
    </ol>
</nav>
{% endblock %}

{% block content %}
<!-- 页面标题 -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0 text-gray-800">
        <i class="fas fa-robot me-2"></i>策略管理
    </h1>
    <div>
        <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#createStrategyModal">
            <i class="fas fa-plus me-1"></i>创建策略
        </button>
        <button class="btn btn-outline-primary" onclick="refreshStrategies()">
            <i class="fas fa-sync-alt me-1"></i>刷新
        </button>
    </div>
</div>

<!-- 策略统计卡片 -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-success shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            运行中策略
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="running-strategies">
                            --
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-play-circle fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-info shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            总策略数
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="total-strategies">
                            --
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-list fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-primary shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            总收益
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="total-profit">
                            --
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-warning shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                            平均胜率
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="avg-win-rate">
                            --
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-percentage fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 策略列表 -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <h6 class="m-0 font-weight-bold text-primary">策略列表</h6>
        <div class="d-flex">
            <select class="form-select form-select-sm me-2" id="status-filter" onchange="filterStrategies()">
                <option value="">全部状态</option>
                <option value="running">运行中</option>
                <option value="stopped">已停止</option>
                <option value="paused">已暂停</option>
                <option value="error">错误</option>
            </select>
            <input type="text" class="form-control form-control-sm" id="search-input" placeholder="搜索策略..." onkeyup="searchStrategies()">
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered" id="strategies-table">
                <thead>
                    <tr>
                        <th>策略名称</th>
                        <th>类型</th>
                        <th>状态</th>
                        <th>交易对</th>
                        <th>总收益</th>
                        <th>胜率</th>
                        <th>最大回撤</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="strategies-tbody">
                    <tr>
                        <td colspan="9" class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 创建策略模态框 -->
<div class="modal fade" id="createStrategyModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">创建新策略</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="create-strategy-form">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">策略名称 *</label>
                                <input type="text" class="form-control" name="name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">策略类型 *</label>
                                <select class="form-select" name="strategy_type" required onchange="onStrategyTypeChange()">
                                    <option value="">请选择</option>
                                    <option value="grid">网格策略</option>
                                    <option value="dca">定投策略</option>
                                    <option value="arbitrage">套利策略</option>
                                    <option value="custom">自定义策略</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">交易所 *</label>
                                <select class="form-select" name="exchange" required>
                                    <option value="">请选择</option>
                                    <option value="binance">币安</option>
                                    <option value="okx">欧易</option>
                                    <option value="huobi">火币</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">交易对 *</label>
                                <input type="text" class="form-control" name="symbol" placeholder="如: BTC/USDT" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">初始资金 *</label>
                                <input type="number" class="form-control" name="initial_balance" step="0.01" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">风险等级</label>
                                <select class="form-select" name="risk_level">
                                    <option value="low">低风险</option>
                                    <option value="medium" selected>中等风险</option>
                                    <option value="high">高风险</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 策略特定参数 -->
                    <div id="strategy-params">
                        <!-- 动态加载策略参数 -->
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="createStrategy()">创建策略</button>
            </div>
        </div>
    </div>
</div>

<!-- 策略详情模态框 -->
<div class="modal fade" id="strategyDetailModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">策略详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="strategy-detail-content">
                <!-- 动态加载策略详情 -->
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
let strategiesData = [];
let filteredStrategies = [];

$(document).ready(function() {
    loadStrategies();
});

function loadStrategies() {
    $.get('/api/v1/strategies')
        .done(function(response) {
            if (response.success) {
                strategiesData = response.data.strategies;
                filteredStrategies = [...strategiesData];
                updateStrategiesTable();
                updateStatistics(response.data.summary);
            }
        })
        .fail(function() {
            showError('加载策略列表失败');
        });
}

function updateStatistics(summary) {
    $('#running-strategies').text(summary.running_count + ' 个');
    $('#total-strategies').text(summary.total_count + ' 个');
    $('#total-profit').text(formatCurrency(summary.total_profit));
    $('#avg-win-rate').text((summary.avg_win_rate * 100).toFixed(1) + '%');
}

function updateStrategiesTable() {
    const tbody = $('#strategies-tbody');
    
    if (filteredStrategies.length === 0) {
        tbody.html('<tr><td colspan="9" class="text-center text-muted">暂无策略</td></tr>');
        return;
    }
    
    let html = '';
    filteredStrategies.forEach(strategy => {
        const statusClass = getStrategyStatusClass(strategy.status);
        const statusText = getStatusText(strategy.status);
        const profitClass = strategy.total_profit >= 0 ? 'text-success' : 'text-danger';
        
        html += `
            <tr>
                <td>
                    <strong>${strategy.name}</strong>
                    <br><small class="text-muted">${strategy.strategy_type}</small>
                </td>
                <td>${getStrategyTypeText(strategy.strategy_type)}</td>
                <td><span class="badge ${statusClass}">${statusText}</span></td>
                <td>${strategy.symbol}</td>
                <td class="${profitClass}">${formatCurrency(strategy.total_profit)}</td>
                <td>${(strategy.win_rate * 100).toFixed(1)}%</td>
                <td class="text-danger">${(strategy.max_drawdown * 100).toFixed(2)}%</td>
                <td>${formatDateTime(strategy.created_at)}</td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary" onclick="viewStrategy('${strategy.id}')" title="查看详情">
                            <i class="fas fa-eye"></i>
                        </button>
                        ${strategy.status === 'running' ? 
                            `<button class="btn btn-outline-warning" onclick="pauseStrategy('${strategy.id}')" title="暂停">
                                <i class="fas fa-pause"></i>
                            </button>` :
                            `<button class="btn btn-outline-success" onclick="startStrategy('${strategy.id}')" title="启动">
                                <i class="fas fa-play"></i>
                            </button>`
                        }
                        <button class="btn btn-outline-danger" onclick="deleteStrategy('${strategy.id}')" title="删除">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
    
    tbody.html(html);
}

function filterStrategies() {
    const statusFilter = $('#status-filter').val();
    const searchTerm = $('#search-input').val().toLowerCase();
    
    filteredStrategies = strategiesData.filter(strategy => {
        const matchesStatus = !statusFilter || strategy.status === statusFilter;
        const matchesSearch = !searchTerm || 
            strategy.name.toLowerCase().includes(searchTerm) ||
            strategy.symbol.toLowerCase().includes(searchTerm) ||
            strategy.strategy_type.toLowerCase().includes(searchTerm);
        
        return matchesStatus && matchesSearch;
    });
    
    updateStrategiesTable();
}

function searchStrategies() {
    filterStrategies();
}

function refreshStrategies() {
    loadStrategies();
}

function onStrategyTypeChange() {
    const strategyType = $('select[name="strategy_type"]').val();
    const paramsContainer = $('#strategy-params');
    
    let html = '';
    
    if (strategyType === 'grid') {
        html = `
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">网格数量</label>
                        <input type="number" class="form-control" name="grid_count" value="10" min="3" max="50">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">价格范围 (%)</label>
                        <input type="number" class="form-control" name="price_range" value="20" min="5" max="100" step="0.1">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">最小价格</label>
                        <input type="number" class="form-control" name="min_price" step="0.01">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">最大价格</label>
                        <input type="number" class="form-control" name="max_price" step="0.01">
                    </div>
                </div>
            </div>
        `;
    } else if (strategyType === 'dca') {
        html = `
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">投资间隔 (小时)</label>
                        <input type="number" class="form-control" name="interval_hours" value="24" min="1">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">每次投资金额</label>
                        <input type="number" class="form-control" name="investment_amount" step="0.01">
                    </div>
                </div>
            </div>
        `;
    }
    
    paramsContainer.html(html);
}

function createStrategy() {
    const form = $('#create-strategy-form');
    const formData = new FormData(form[0]);
    const data = Object.fromEntries(formData.entries());
    
    // 验证必填字段
    if (!data.name || !data.strategy_type || !data.exchange || !data.symbol || !data.initial_balance) {
        showError('请填写所有必填字段');
        return;
    }
    
    $.ajax({
        url: '/api/v1/strategies',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function(response) {
            if (response.success) {
                $('#createStrategyModal').modal('hide');
                form[0].reset();
                loadStrategies();
                showSuccess('策略创建成功');
            } else {
                showError(response.message || '创建策略失败');
            }
        },
        error: function() {
            showError('创建策略失败');
        }
    });
}

function viewStrategy(strategyId) {
    $.get(`/api/v1/strategies/${strategyId}`)
        .done(function(response) {
            if (response.success) {
                showStrategyDetail(response.data);
            }
        })
        .fail(function() {
            showError('加载策略详情失败');
        });
}

function showStrategyDetail(strategy) {
    const content = $('#strategy-detail-content');
    
    const html = `
        <div class="row">
            <div class="col-md-6">
                <h6>基本信息</h6>
                <table class="table table-sm">
                    <tr><td>策略名称:</td><td>${strategy.name}</td></tr>
                    <tr><td>策略类型:</td><td>${getStrategyTypeText(strategy.strategy_type)}</td></tr>
                    <tr><td>交易所:</td><td>${strategy.exchange}</td></tr>
                    <tr><td>交易对:</td><td>${strategy.symbol}</td></tr>
                    <tr><td>状态:</td><td><span class="badge ${getStrategyStatusClass(strategy.status)}">${getStatusText(strategy.status)}</span></td></tr>
                    <tr><td>创建时间:</td><td>${formatDateTime(strategy.created_at)}</td></tr>
                </table>
            </div>
            <div class="col-md-6">
                <h6>收益统计</h6>
                <table class="table table-sm">
                    <tr><td>总收益:</td><td class="${strategy.total_profit >= 0 ? 'text-success' : 'text-danger'}">${formatCurrency(strategy.total_profit)}</td></tr>
                    <tr><td>胜率:</td><td>${(strategy.win_rate * 100).toFixed(1)}%</td></tr>
                    <tr><td>最大回撤:</td><td class="text-danger">${(strategy.max_drawdown * 100).toFixed(2)}%</td></tr>
                    <tr><td>总交易次数:</td><td>${strategy.total_trades}</td></tr>
                    <tr><td>盈利交易:</td><td class="text-success">${strategy.winning_trades}</td></tr>
                    <tr><td>亏损交易:</td><td class="text-danger">${strategy.losing_trades}</td></tr>
                </table>
            </div>
        </div>
        
        <div class="row mt-4">
            <div class="col-12">
                <h6>策略参数</h6>
                <pre class="bg-light p-3 rounded">${JSON.stringify(strategy.parameters, null, 2)}</pre>
            </div>
        </div>
        
        <div class="row mt-4">
            <div class="col-12">
                <h6>描述</h6>
                <p>${strategy.description || '暂无描述'}</p>
            </div>
        </div>
    `;
    
    content.html(html);
    $('#strategyDetailModal').modal('show');
}

function startStrategy(strategyId) {
    if (!confirm('确定要启动这个策略吗？')) return;
    
    $.ajax({
        url: `/api/v1/strategies/${strategyId}/start`,
        method: 'POST',
        success: function(response) {
            if (response.success) {
                loadStrategies();
                showSuccess('策略启动成功');
            } else {
                showError(response.message || '启动策略失败');
            }
        },
        error: function() {
            showError('启动策略失败');
        }
    });
}

function pauseStrategy(strategyId) {
    if (!confirm('确定要暂停这个策略吗？')) return;
    
    $.ajax({
        url: `/api/v1/strategies/${strategyId}/pause`,
        method: 'POST',
        success: function(response) {
            if (response.success) {
                loadStrategies();
                showSuccess('策略暂停成功');
            } else {
                showError(response.message || '暂停策略失败');
            }
        },
        error: function() {
            showError('暂停策略失败');
        }
    });
}

function deleteStrategy(strategyId) {
    if (!confirm('确定要删除这个策略吗？此操作不可恢复！')) return;
    
    $.ajax({
        url: `/api/v1/strategies/${strategyId}`,
        method: 'DELETE',
        success: function(response) {
            if (response.success) {
                loadStrategies();
                showSuccess('策略删除成功');
            } else {
                showError(response.message || '删除策略失败');
            }
        },
        error: function() {
            showError('删除策略失败');
        }
    });
}

function getStrategyStatusClass(status) {
    const classMap = {
        'running': 'bg-success',
        'stopped': 'bg-secondary',
        'error': 'bg-danger',
        'paused': 'bg-warning'
    };
    return classMap[status] || 'bg-secondary';
}

function getStatusText(status) {
    const statusMap = {
        'running': '运行中',
        'stopped': '已停止',
        'error': '错误',
        'paused': '已暂停'
    };
    return statusMap[status] || status;
}

function getStrategyTypeText(type) {
    const typeMap = {
        'grid': '网格策略',
        'dca': '定投策略',
        'arbitrage': '套利策略',
        'custom': '自定义策略'
    };
    return typeMap[type] || type;
}

function formatCurrency(amount) {
    return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY'
    }).format(amount);
}

function formatDateTime(timestamp) {
    return new Date(timestamp).toLocaleString('zh-CN');
}

function showError(message) {
    const alert = `
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    $('main').prepend(alert);
}

function showSuccess(message) {
    const alert = `
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    $('main').prepend(alert);
}
</script>
{% endblock %}